#include "collectiontreemodel.h"
#include "data.h"

#include <QStringList>
#include <QDebug>

CollectionTreeModel::CollectionTreeModel(QObject *parent) :
    ItemTreeModel(parent)
{
}

QVariant CollectionTreeModel::data(const QModelIndex &index, int role) const
{
    switch (role)
    {
    case Qt::DisplayRole:
        return ItemTreeModel::data(index, role);

    case Qt::EditRole:
        break;

    default:
        return QVariant();
    }


    Item* item = qobject_cast<Item*>(itemFromIndex(index));
    if (!item) return QVariant();

    QStringList options = item->options(index.column());
    if (options.isEmpty()) return ItemTreeModel::data(index, Qt::DisplayRole);

    return options;
}

Qt::ItemFlags CollectionTreeModel::flags(const QModelIndex &index) const
{
    Item* item = qobject_cast<Item*>(itemFromIndex(index));
    if (!item) return (ItemTreeModel::flags(index) | Qt::ItemIsEditable);

    MetaData* meta = item->metaData();
    if (!meta) return ItemTreeModel::flags(index);

    MetaItem* metaItem = meta->item(index.column());
    if (!metaItem || !metaItem->editable()) return ItemTreeModel::flags(index);

    return (ItemTreeModel::flags(index) | Qt::ItemIsEditable);
}

AbstractData *CollectionTreeModel::dataFromIndex(const QModelIndex &index) const
{
    return qobject_cast<AbstractData*>(itemFromIndex(index));
}

void CollectionTreeModel::setRoot(AbstractModelItem *root)
{
    if (m_root.data() == root) return;

    if (!m_root.isNull())
    {
        disconnect(m_root.data(), SIGNAL(sigChanged()), this, SLOT(onChanged()));
    }

    emit layoutAboutToBeChanged();
    ItemTreeModel::setRoot(root);
    emit layoutChanged();


    if (root)
    {
        connect(root, SIGNAL(sigChanged()), this, SLOT(onChanged()));
    }

}


void CollectionTreeModel::onChanged()
{
    QModelIndex topLeft = index(0,0, QModelIndex());

    int lastRow = rowCount(QModelIndex())-1;
    int lastCol = columnCount(QModelIndex());

    QModelIndex bottomRight = topLeft.sibling(lastRow, 0);
    while (hasChildren(bottomRight))
    {
        lastRow = rowCount(bottomRight)-1;
        bottomRight = bottomRight.child(lastRow, 0);
    }

    bottomRight = bottomRight.sibling(bottomRight.row(), lastCol);
    emit dataChanged(topLeft, bottomRight);
}







